﻿///////////////////////////////////////////////////////////////////////////////
// Activity: program.activity0
// ArmMover service implementation
///////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml;

using ccr = Microsoft.Ccr.Core;
using dss = Microsoft.Dss.Core;
using dssa = Microsoft.Dss.Core.Attributes;
using dssh = Microsoft.Dss.Core.DsspHttp;
using dssm = Microsoft.Dss.ServiceModel.DsspServiceBase;
using dssp = Microsoft.Dss.ServiceModel.Dssp;
using soap = W3C.Soap;

using submgr = Microsoft.Dss.Services.SubscriptionManager;
using timer = Microsoft.Robotics.Services.Sample.Timer.Proxy;
using articulatedarm = Microsoft.Robotics.Services.ArticulatedArm.Proxy;
using sound = Microsoft.Robotics.Services.Sample.Sound.Proxy;
using xinputgamepad = Microsoft.Robotics.Services.Sample.XInputGamepad.Proxy;

namespace Robotics.Movearm_real2.ArmMover
{
    [DisplayName("Movearm_real2ArmMover")]
    [Description("Move the Lynx L6 arm with an Xbox controller.")]
    [dssa.Contract(Contract.Identifier)]
    public class ArmMoverService : dssm.DsspServiceBase
    {
        // Service state
        [dssa.InitialStatePartner(Optional = true)]
        private ArmMoverState _state;

        // Service operations port
        [dssa.ServicePort("/Movearm_real2/ArmMover", AllowMultipleInstances = false)]
        private ArmMoverOperations _mainPort = new ArmMoverOperations();

        #region Partner services

        [dssa.Partner("SubMgr", Contract = submgr.Contract.Identifier, CreationPolicy = dssa.PartnerCreationPolicy.CreateAlways)]
        private submgr.SubscriptionManagerPort _subMgr = new submgr.SubscriptionManagerPort();

        // Partner: Timer, Contract: http://schemas.microsoft.com/robotics/2006/08/timer.html
        [dssa.Partner("Timer", Contract = timer.Contract.Identifier, CreationPolicy = dssa.PartnerCreationPolicy.UsePartnerListEntry)]
        timer.TimerOperations _timerPort = new timer.TimerOperations();

        // Partner: SoundPlayer, Contract: http://schemas.microsoft.com/robotics/2006/08/sound.html
        [dssa.Partner("SoundPlayer", Contract = sound.Contract.Identifier, CreationPolicy = dssa.PartnerCreationPolicy.UsePartnerListEntry)]
        sound.SoundOperations _soundPlayerPort = new sound.SoundOperations();

        // Partner: Timer0, Contract: http://schemas.microsoft.com/robotics/2006/08/timer.html
        [dssa.Partner("Timer0", Contract = timer.Contract.Identifier, CreationPolicy = dssa.PartnerCreationPolicy.UsePartnerListEntry)]
        timer.TimerOperations _timer0Port = new timer.TimerOperations();

        // Partner: XInputController, Contract: http://schemas.microsoft.com/robotics/2006/09/xinputgamepad.html
        [dssa.Partner("XInputController", Contract = xinputgamepad.Contract.Identifier, CreationPolicy = dssa.PartnerCreationPolicy.UsePartnerListEntry)]
        xinputgamepad.XInputGamepadOperations _xInputControllerPort = new xinputgamepad.XInputGamepadOperations();

        // Partner: LynxMotionLynx6Arm, Contract: http://schemas.microsoft.com/2006/06/articulatedarm.html
        [dssa.Partner("LynxMotionLynx6Arm", Contract = articulatedarm.Contract.Identifier, CreationPolicy = dssa.PartnerCreationPolicy.UsePartnerListEntry)]
        articulatedarm.ArticulatedArmOperations _lynxMotionLynx6ArmPort = new articulatedarm.ArticulatedArmOperations();

        #endregion

        public ArmMoverService(dssp.DsspServiceCreationPort creationPort)
            : base(creationPort)
        {
        }

        protected override void Start()
        {
            // If there was no initial state partner, then the service state will be null.
            if (_state == null)
            {
                // The state MUST be created before the service starts processing messages.
                _state = new ArmMoverState();
            }

            // The rest of the start process requires the ability to wait for responses from
            // services and from the start handler (if any). So execution now proceeds in an
            // iterator function.
            SpawnIterator(DoStart);
        }

        private IEnumerator<ccr.ITask> DoStart()
        {

            // Start the RunHandler, this represents the parts of the diagram that
            // are are not run in the context of an operation or notification.
            StartHandler start = new StartHandler(this, Environment.TaskQueue);
            SpawnIterator(start.RunHandler);
            // Wait until the RunHandler has completed.
            yield return ccr.Arbiter.Receive(false, start.Complete, EmptyHandler);

            // Start operation handlers and insert into directory service.
            StartHandlers();

            yield break;
        }

        private void StartHandlers()
        {
            // Activate message handlers for this service and insert into the directory.
            base.Start();
        }

        #region Standard DSS message handlers

        [dssa.ServiceHandler(dssa.ServiceHandlerBehavior.Concurrent)]
        public virtual IEnumerator<ccr.ITask> GetHandler(Get get)
        {
            get.ResponsePort.Post(_state);
            yield break;
        }

        [dssa.ServiceHandler(dssa.ServiceHandlerBehavior.Concurrent)]
        public virtual IEnumerator<ccr.ITask> HttpGetHandler(dssh.HttpGet httpGet)
        {
            httpGet.ResponsePort.Post(new dssh.HttpResponseType(_state));
            yield break;
        }

        [dssa.ServiceHandler(dssa.ServiceHandlerBehavior.Exclusive)]
        public virtual IEnumerator<ccr.ITask> ReplaceHandler(Replace replace)
        {
            _state = replace.Body;

            replace.ResponsePort.Post(dssp.DefaultReplaceResponseType.Instance);
            base.SendNotification<Replace>(_subMgr, replace);

            yield break;
        }

        [dssa.ServiceHandler(dssa.ServiceHandlerBehavior.Concurrent)]
        public virtual IEnumerator<ccr.ITask> SubscribeHandler(Subscribe subscribe)
        {
            dssp.SubscribeRequestType request = subscribe.Body;

            yield return ccr.Arbiter.Choice(
                SubscribeHelper(_subMgr, request, subscribe.ResponsePort),
                delegate(ccr.SuccessResult success)
                {
                    base.SendNotification<Replace>(_subMgr, request.Subscriber, _state);
                },
                delegate(Exception e) { }
            );
        }

        #endregion

        #region Custom message handlers

        [dssa.ServiceHandler(dssa.ServiceHandlerBehavior.Exclusive)]
        public virtual IEnumerator<ccr.ITask> SetPollIntervalHandler(SetPollInterval message)
        {
            SetPollIntervalMessageHandler handler = new SetPollIntervalMessageHandler(this, Environment.TaskQueue);

            SpawnIterator(message.Body, message.ResponsePort, handler.RunHandler);

            yield return ccr.Arbiter.Receive(false, handler.Complete, EmptyHandler);

            if (handler.StateChanged == true)
            {
                base.SendNotification<Replace>(_subMgr, _state);
            }
        }

        #endregion

        #region StartHandler class

        class StartHandler : HandlerBase
        {
            ///////////////////////////////////////////////////////////////////
            // program.activity0.Start+start
            // expr - set
            // expr0 - set0
            // expr1 - set1
            // expr2 - set2
            // expr100 - set100
            // expr101 - set101
            // snippet.element
            ///////////////////////////////////////////////////////////////////

            public StartHandler(ArmMoverService service, ccr.DispatcherQueue queue)
                : base(service, queue)
            {
            }

            ///////////////////////////////////////////////////////////////////
            // program.activity0.Start+start
            // snippet.element
            // expr101 - set101
            // expr100 - set100
            // expr2 - set2
            // expr1 - set1
            // expr0 - set0
            // expr - set
            ///////////////////////////////////////////////////////////////////

            public IEnumerator<ccr.ITask> RunHandler()
            {
                Increment();



                base.StateChanged = true;
                State.CosA = (float)FloatCast(1);

                base.StateChanged = true;
                State.SinA = (float)FloatCast(0);

                base.StateChanged = true;
                State.Angle = (float)FloatCast(0);

                base.StateChanged = true;
                State.Z = (float)FloatCast(0);

                base.StateChanged = true;
                State.Y = FloatCast(0.15F);

                base.StateChanged = true;
                State.X = FloatCast(-0.2F);

                Decrement();

                yield return WaitUntilComplete();
            }
        }

        #endregion

        #region SetPollIntervalMessageHandler class

        class SetPollIntervalMessageHandler : HandlerBase
        {
            ///////////////////////////////////////////////////////////////////
            // request
            // expr - set - expr0
            // element
            // __use__0.snippet0.snippet.noop - __use__0.snippet0.snippet.expr - __use__0.snippet0.snippet.join
            // __use__0.snippet0.call - __use__0.snippet0.call.iftype
            // __use__.snippet0.call - __use__.snippet0.call.iftype
            // if if{expr3 - set3}elseif{expr30 - set30}elseif{expr31 - set31}elseif{expr300 - set300}else{}
            // if0 if{expr32 - set32}elseif{expr301 - set301}elseif{expr310 - set310}elseif{expr3000 - set3000}else{}
            // if1 if{expr33 - set33}elseif{expr302 - set302}elseif{expr311 - set311}elseif{expr3001 - set3001}else{}
            // if2 if{expr330 - set330}elseif{expr3020 - set3020}else{}
            // if3 if{expr4 - set0}elseif{expr5 - set1}else{}
            // if10 if{expr2 - set2}elseif{expr21 - set20}elseif{expr210 - set21}elseif{expr211 - set22}else{}
            // expr1 - &element
            // element2
            // __use__400.snippet0.snippet.noop - [(__use__400.snippet0.snippet.snippet0.noop - [(__use__400.snippet0.snippet.snippet0.expr0 - __use__400.snippet0.snippet.snippet0.join)(__use__400.snippet0.snippet.snippet0.snippet.noop - [(__use__400.snippet0.snippet.snippet0.snippet.expr1 - __use__400.snippet0.snippet.snippet0.snippet.join)(__use__400.snippet0.snippet.snippet0.snippet.expr0 - &__use__400.snippet0.snippet.snippet0.snippet.join)(__use__400.snippet0.snippet.snippet0.snippet.expr - &__use__400.snippet0.snippet.snippet0.snippet.join)] - &__use__400.snippet0.snippet.snippet0.join)] - __use__400.snippet0.snippet.join)(__use__400.snippet0.snippet.snippet.noop - [(__use__400.snippet0.snippet.snippet.expr1 - __use__400.snippet0.snippet.snippet.join)(__use__400.snippet0.snippet.snippet.expr0 - &__use__400.snippet0.snippet.snippet.join)(__use__400.snippet0.snippet.snippet.expr - &__use__400.snippet0.snippet.snippet.join)] - &__use__400.snippet0.snippet.join)(__use__400.snippet0.snippet.expr - &__use__400.snippet0.snippet.join)] - __use__400.snippet0.call - __use__400.snippet0.call.iftype
            // &element1
            // __use__4.snippet0.snippet.noop - [(__use__4.snippet0.snippet.snippet0.noop - [(__use__4.snippet0.snippet.snippet0.expr0 - __use__4.snippet0.snippet.snippet0.join)(__use__4.snippet0.snippet.snippet0.snippet.noop - [(__use__4.snippet0.snippet.snippet0.snippet.expr1 - __use__4.snippet0.snippet.snippet0.snippet.join)(__use__4.snippet0.snippet.snippet0.snippet.expr0 - &__use__4.snippet0.snippet.snippet0.snippet.join)(__use__4.snippet0.snippet.snippet0.snippet.expr - &__use__4.snippet0.snippet.snippet0.snippet.join)] - &__use__4.snippet0.snippet.snippet0.join)] - __use__4.snippet0.snippet.join)(__use__4.snippet0.snippet.snippet.noop - [(__use__4.snippet0.snippet.snippet.expr1 - __use__4.snippet0.snippet.snippet.join)(__use__4.snippet0.snippet.snippet.expr0 - &__use__4.snippet0.snippet.snippet.join)(__use__4.snippet0.snippet.snippet.expr - &__use__4.snippet0.snippet.snippet.join)] - &__use__4.snippet0.snippet.join)(__use__4.snippet0.snippet.expr - &__use__4.snippet0.snippet.join)] - __use__4.snippet0.call - __use__4.snippet0.call.iftype
            // &element1
            // __use__40.snippet.snippet.noop - [(__use__40.snippet.snippet.snippet0.noop - [(__use__40.snippet.snippet.snippet0.expr0 - __use__40.snippet.snippet.snippet0.join)(__use__40.snippet.snippet.snippet0.snippet.noop - [(__use__40.snippet.snippet.snippet0.snippet.expr1 - __use__40.snippet.snippet.snippet0.snippet.join)(__use__40.snippet.snippet.snippet0.snippet.expr0 - &__use__40.snippet.snippet.snippet0.snippet.join)(__use__40.snippet.snippet.snippet0.snippet.expr - &__use__40.snippet.snippet.snippet0.snippet.join)] - &__use__40.snippet.snippet.snippet0.join)] - __use__40.snippet.snippet.join)(__use__40.snippet.snippet.snippet.noop - [(__use__40.snippet.snippet.snippet.expr1 - __use__40.snippet.snippet.snippet.join)(__use__40.snippet.snippet.snippet.expr0 - &__use__40.snippet.snippet.snippet.join)(__use__40.snippet.snippet.snippet.expr - &__use__40.snippet.snippet.snippet.join)] - &__use__40.snippet.snippet.join)(__use__40.snippet.snippet.expr - &__use__40.snippet.snippet.join)] - __use__40.snippet.call - __use__40.snippet.call.iftype
            // &element1
            // __use__401.snippet0.snippet.noop - [(__use__401.snippet0.snippet.snippet0.noop - [(__use__401.snippet0.snippet.snippet0.expr0 - __use__401.snippet0.snippet.snippet0.join)(__use__401.snippet0.snippet.snippet0.snippet.noop - [(__use__401.snippet0.snippet.snippet0.snippet.expr1 - __use__401.snippet0.snippet.snippet0.snippet.join)(__use__401.snippet0.snippet.snippet0.snippet.expr0 - &__use__401.snippet0.snippet.snippet0.snippet.join)(__use__401.snippet0.snippet.snippet0.snippet.expr - &__use__401.snippet0.snippet.snippet0.snippet.join)] - &__use__401.snippet0.snippet.snippet0.join)] - __use__401.snippet0.snippet.join)(__use__401.snippet0.snippet.snippet.noop - [(__use__401.snippet0.snippet.snippet.expr1 - __use__401.snippet0.snippet.snippet.join)(__use__401.snippet0.snippet.snippet.expr0 - &__use__401.snippet0.snippet.snippet.join)(__use__401.snippet0.snippet.snippet.expr - &__use__401.snippet0.snippet.snippet.join)] - &__use__401.snippet0.snippet.join)(__use__401.snippet0.snippet.expr - &__use__401.snippet0.snippet.join)] - __use__401.snippet0.call - __use__401.snippet0.call.iftype
            // &element1
            // __use__4010.snippet.snippet.noop - [(__use__4010.snippet.snippet.snippet0.noop - [(__use__4010.snippet.snippet.snippet0.expr0 - __use__4010.snippet.snippet.snippet0.join)(__use__4010.snippet.snippet.snippet0.snippet.noop - [(__use__4010.snippet.snippet.snippet0.snippet.expr1 - __use__4010.snippet.snippet.snippet0.snippet.join)(__use__4010.snippet.snippet.snippet0.snippet.expr0 - &__use__4010.snippet.snippet.snippet0.snippet.join)(__use__4010.snippet.snippet.snippet0.snippet.expr - &__use__4010.snippet.snippet.snippet0.snippet.join)] - &__use__4010.snippet.snippet.snippet0.join)] - __use__4010.snippet.snippet.join)(__use__4010.snippet.snippet.snippet.noop - [(__use__4010.snippet.snippet.snippet.expr1 - __use__4010.snippet.snippet.snippet.join)(__use__4010.snippet.snippet.snippet.expr0 - &__use__4010.snippet.snippet.snippet.join)(__use__4010.snippet.snippet.snippet.expr - &__use__4010.snippet.snippet.snippet.join)] - &__use__4010.snippet.snippet.join)(__use__4010.snippet.snippet.expr - &__use__4010.snippet.snippet.join)] - __use__4010.snippet.call - __use__4010.snippet.call.iftype
            // &element1
            // __use__4011.snippet.snippet.noop - [(__use__4011.snippet.snippet.snippet0.noop - [(__use__4011.snippet.snippet.snippet0.expr0 - __use__4011.snippet.snippet.snippet0.join)(__use__4011.snippet.snippet.snippet0.snippet.noop - [(__use__4011.snippet.snippet.snippet0.snippet.expr1 - __use__4011.snippet.snippet.snippet0.snippet.join)(__use__4011.snippet.snippet.snippet0.snippet.expr0 - &__use__4011.snippet.snippet.snippet0.snippet.join)(__use__4011.snippet.snippet.snippet0.snippet.expr - &__use__4011.snippet.snippet.snippet0.snippet.join)] - &__use__4011.snippet.snippet.snippet0.join)] - __use__4011.snippet.snippet.join)(__use__4011.snippet.snippet.snippet.noop - [(__use__4011.snippet.snippet.snippet.expr1 - __use__4011.snippet.snippet.snippet.join)(__use__4011.snippet.snippet.snippet.expr0 - &__use__4011.snippet.snippet.snippet.join)(__use__4011.snippet.snippet.snippet.expr - &__use__4011.snippet.snippet.snippet.join)] - &__use__4011.snippet.snippet.join)(__use__4011.snippet.snippet.expr - &__use__4011.snippet.snippet.join)] - __use__4011.snippet.call - __use__4011.snippet.call.iftype
            // element1
            // __use__1.snippet0.snippet.noop - __use__1.snippet0.snippet.expr - __use__1.snippet0.snippet.join
            // __use__1.snippet0.call - __use__1.snippet0.call.iftype
            // [(__use__2.snippet.snippet.noop - __use__2.snippet.snippet.expr - __use__2.snippet.snippet.join)] - __use__2.snippet.call - __use__2.snippet.call.iftype
            // expr2020
            // snippet.element
            // expr20
            ///////////////////////////////////////////////////////////////////

            public SetPollIntervalMessageHandler(ArmMoverService service, ccr.DispatcherQueue queue)
                : base(service, queue)
            {

                // Activate merge handlers
                Activate(ccr.Arbiter.Receive(true, _mergeAlpha, _mergeAlphaHandler));
                Activate(ccr.Arbiter.Receive(true, _mergeBeta, _mergeBetaHandler));
                Activate(ccr.Arbiter.Receive(true, _mergeGamma, _mergeGammaHandler));

                // Register joins with base class to manage active count for incomplete joins.
                base.RegisterJoin(_joinAlphaPorts);
                base.RegisterJoin(_joinBetaPorts);
                // Activate Join handlers
                Activate(ccr.Arbiter.MultiplePortReceive(true, _joinAlphaPorts, _joinAlphaHandler));
                Activate(ccr.Arbiter.MultiplePortReceive(true, _joinBetaPorts, _joinBetaHandler));
            }

            dssp.DsspResponsePort<SetPollIntervalResponse> _responsePort;

            ///////////////////////////////////////////////////////////////////
            // request
            // expr20
            // expr - set - expr0
            // snippet.element
            // element
            ///////////////////////////////////////////////////////////////////

            public IEnumerator<ccr.ITask> RunHandler(SetPollIntervalRequest message, dssp.DsspResponsePort<SetPollIntervalResponse> responsePort)
            {
                _responsePort = responsePort;
                Increment();



                base.StateChanged = true;

                ArmMoverState a = new ArmMoverState();
                State.PollInterval = message.PollInterval;
                a.PollInterval = State.PollInterval;

                _responsePort.Post(new SetPollIntervalResponse());


                Increment();
                _mergeAlpha.Post(State.PollInterval);

                Decrement();

                yield return WaitUntilComplete();
            }

            ccr.Port<int> _mergeAlpha = new ccr.Port<int>();

            ///////////////////////////////////////////////////////////////////
            // __use__0.snippet0.snippet.noop - __use__0.snippet0.snippet.expr - __use__0.snippet0.snippet.join
            ///////////////////////////////////////////////////////////////////

            void _mergeAlphaHandler(int message)
            {
                Increment();
                _joinAlphaPorts[0].Post(message);

                Decrement();
            }

            ///////////////////////////////////////////////////////////////////
            // __use__0.snippet0.call - __use__0.snippet0.call.iftype
            ///////////////////////////////////////////////////////////////////

            void _joinAlphaHandler(object[] args)
            {
                JoinAlpha message = new JoinAlpha(args);

                Increment();
                Activate(
                    ccr.Arbiter.Choice(
                        TimerPort.Wait((timer.SetTimerRequest)message),
                        OnWaitSuccess,
                        delegate(soap.Fault fault)
                        {
                            base.FaultHandler(fault, @"TimerPort.Wait((timer.SetTimerRequest)message)");
                            Decrement();
                        }
                    )
                );

                Decrement(args.Length);
            }

            ///////////////////////////////////////////////////////////////////
            // __use__1.snippet0.call - __use__1.snippet0.call.iftype
            ///////////////////////////////////////////////////////////////////

            void _joinBetaHandler(object[] args)
            {
                JoinBeta message = new JoinBeta(args);

                Increment();
                Activate(
                    ccr.Arbiter.Choice(
                        SoundPlayerPort.Beep((sound.BeepRequest)message),
                        OnBeepSuccess,
                        delegate(soap.Fault fault)
                        {
                            base.FaultHandler(fault, @"SoundPlayerPort.Beep((sound.BeepRequest)message)");
                            Decrement();
                        }
                    )
                );

                Decrement(args.Length);
            }

            void OnWaitSuccess(dssp.DefaultSubmitResponseType response)
            {

                Increment();
                _mergeBeta.Post(response);


                Increment();
                _mergeAlpha.Post(State.PollInterval);


                Increment();
                Activate(
                    ccr.Arbiter.Choice(
                        XInputControllerPort.Get(new dssp.GetRequestType()),
                        OnGetRequestTypeSuccess,
                        delegate(soap.Fault fault)
                        {
                            base.FaultHandler(fault, @"XInputControllerPort.Get(new dssp.GetRequestType())");
                            Decrement();
                        }
                    )
                );

                Decrement();
            }

            void OnBeepSuccess(dssp.DefaultSubmitResponseType response)
            {
                timer.SetTimerRequest request = new timer.SetTimerRequest();
                request.Interval = 1000;

                Increment();
                Activate(
                    ccr.Arbiter.Choice(
                        Timer0Port.Wait(request),
                        OnWait1Success,
                        delegate(soap.Fault fault)
                        {
                            base.FaultHandler(fault, @"Timer0Port.Wait(request)");
                            Decrement();
                        }
                    )
                );

                Decrement();
            }

            void OnGetRequestTypeSuccess(xinputgamepad.XInputGamepadState response)
            {

                if (response.Thumbsticks.RightX > 0.8D)
                {
                    base.StateChanged = true;
                    State.WristRotate4 = FloatCast(State.WristRotate4 - 0.025D);
                }
                else if (response.Thumbsticks.RightX < -0.8D)
                {
                    base.StateChanged = true;
                    State.WristRotate4 = FloatCast(State.WristRotate4 + 0.025D);
                }
                else if (response.Thumbsticks.RightX > 0.1D)
                {
                    base.StateChanged = true;
                    State.WristRotate4 = FloatCast(State.WristRotate4 - 0.01D);
                }
                else if (response.Thumbsticks.RightX < -0.1D)
                {
                    base.StateChanged = true;
                    State.WristRotate4 = FloatCast(State.WristRotate4 + 0.01D);
                }


                if (response.Buttons.X)
                {
                    base.StateChanged = true;
                    State.Gripper5 = FloatCast(State.Gripper5 - 0.02D);
                }
                else if (response.Buttons.B)
                {
                    base.StateChanged = true;
                    State.Gripper5 = FloatCast(State.Gripper5 + 0.02D);
                }


                if (response.Buttons.Y)
                {
                    base.StateChanged = true;
                    State.Wrist3 = FloatCast(State.Wrist3 + 0.02D);
                }
                else if (response.Buttons.A)
                {
                    base.StateChanged = true;
                    State.Wrist3 = FloatCast(State.Wrist3 - 0.02D);
                }


                if (response.Thumbsticks.RightY > 0.8D)
                {
                    base.StateChanged = true;
                    State.Elbow2 = FloatCast(State.Elbow2 + 0.025D);
                }
                else if (response.Thumbsticks.RightY < -0.8D)
                {
                    base.StateChanged = true;
                    State.Elbow2 = FloatCast(State.Elbow2 - 0.025D);
                }
                else if (response.Thumbsticks.RightY > 0.1D)
                {
                    base.StateChanged = true;
                    State.Elbow2 = FloatCast(State.Elbow2 + 0.01D);
                }
                else if (response.Thumbsticks.RightY < -0.1D)
                {
                    base.StateChanged = true;
                    State.Elbow2 = FloatCast(State.Elbow2 - 0.01D);
                }


                if (response.Thumbsticks.LeftY > 0.8D)
                {
                    base.StateChanged = true;
                    State.Shoulder1 = FloatCast(State.Shoulder1 - 0.025D);
                }
                else if (response.Thumbsticks.LeftY < -0.8D)
                {
                    base.StateChanged = true;
                    State.Shoulder1 = FloatCast(State.Shoulder1 + 0.025D);
                }
                else if (response.Thumbsticks.LeftY > 0.1D)
                {
                    base.StateChanged = true;
                    State.Shoulder1 = FloatCast(State.Shoulder1 - 0.01D);
                }
                else if (response.Thumbsticks.LeftY < -0.1D)
                {
                    base.StateChanged = true;
                    State.Shoulder1 = FloatCast(State.Shoulder1 + 0.01D);
                }


                if (response.Thumbsticks.LeftX > 0.8D)
                {
                    base.StateChanged = true;
                    State.Base0 = FloatCast(State.Base0 + 0.025D);
                }
                else if (response.Thumbsticks.LeftX < -0.8D)
                {
                    base.StateChanged = true;
                    State.Base0 = FloatCast(State.Base0 - 0.025D);
                }
                else if (response.Thumbsticks.LeftX > 0.1D)
                {
                    base.StateChanged = true;
                    State.Base0 = FloatCast(State.Base0 + 0.01D);
                }
                else if (response.Thumbsticks.LeftX < -0.1D)
                {
                    base.StateChanged = true;
                    State.Base0 = FloatCast(State.Base0 - 0.01D);
                }

                Decrement();
            }

            void OnWait1Success(dssp.DefaultSubmitResponseType response)
            {

                Decrement();
            }

            ccr.Port<dssp.DefaultSubmitResponseType> _mergeBeta = new ccr.Port<dssp.DefaultSubmitResponseType>();

            ///////////////////////////////////////////////////////////////////
            // __use__4011.snippet.snippet.noop - [(__use__4011.snippet.snippet.snippet0.noop - [(__use__4011.snippet.snippet.snippet0.expr0 - __use__4011.snippet.snippet.snippet0.join)(__use__4011.snippet.snippet.snippet0.snippet.noop - [(__use__4011.snippet.snippet.snippet0.snippet.expr1 - __use__4011.snippet.snippet.snippet0.snippet.join)(__use__4011.snippet.snippet.snippet0.snippet.expr0 - &__use__4011.snippet.snippet.snippet0.snippet.join)(__use__4011.snippet.snippet.snippet0.snippet.expr - &__use__4011.snippet.snippet.snippet0.snippet.join)] - &__use__4011.snippet.snippet.snippet0.join)] - __use__4011.snippet.snippet.join)(__use__4011.snippet.snippet.snippet.noop - [(__use__4011.snippet.snippet.snippet.expr1 - __use__4011.snippet.snippet.snippet.join)(__use__4011.snippet.snippet.snippet.expr0 - &__use__4011.snippet.snippet.snippet.join)(__use__4011.snippet.snippet.snippet.expr - &__use__4011.snippet.snippet.snippet.join)] - &__use__4011.snippet.snippet.join)(__use__4011.snippet.snippet.expr - &__use__4011.snippet.snippet.join)] - __use__4011.snippet.call - __use__4011.snippet.call.iftype
            // __use__4010.snippet.snippet.noop - [(__use__4010.snippet.snippet.snippet0.noop - [(__use__4010.snippet.snippet.snippet0.expr0 - __use__4010.snippet.snippet.snippet0.join)(__use__4010.snippet.snippet.snippet0.snippet.noop - [(__use__4010.snippet.snippet.snippet0.snippet.expr1 - __use__4010.snippet.snippet.snippet0.snippet.join)(__use__4010.snippet.snippet.snippet0.snippet.expr0 - &__use__4010.snippet.snippet.snippet0.snippet.join)(__use__4010.snippet.snippet.snippet0.snippet.expr - &__use__4010.snippet.snippet.snippet0.snippet.join)] - &__use__4010.snippet.snippet.snippet0.join)] - __use__4010.snippet.snippet.join)(__use__4010.snippet.snippet.snippet.noop - [(__use__4010.snippet.snippet.snippet.expr1 - __use__4010.snippet.snippet.snippet.join)(__use__4010.snippet.snippet.snippet.expr0 - &__use__4010.snippet.snippet.snippet.join)(__use__4010.snippet.snippet.snippet.expr - &__use__4010.snippet.snippet.snippet.join)] - &__use__4010.snippet.snippet.join)(__use__4010.snippet.snippet.expr - &__use__4010.snippet.snippet.join)] - __use__4010.snippet.call - __use__4010.snippet.call.iftype
            // __use__401.snippet0.snippet.noop - [(__use__401.snippet0.snippet.snippet0.noop - [(__use__401.snippet0.snippet.snippet0.expr0 - __use__401.snippet0.snippet.snippet0.join)(__use__401.snippet0.snippet.snippet0.snippet.noop - [(__use__401.snippet0.snippet.snippet0.snippet.expr1 - __use__401.snippet0.snippet.snippet0.snippet.join)(__use__401.snippet0.snippet.snippet0.snippet.expr0 - &__use__401.snippet0.snippet.snippet0.snippet.join)(__use__401.snippet0.snippet.snippet0.snippet.expr - &__use__401.snippet0.snippet.snippet0.snippet.join)] - &__use__401.snippet0.snippet.snippet0.join)] - __use__401.snippet0.snippet.join)(__use__401.snippet0.snippet.snippet.noop - [(__use__401.snippet0.snippet.snippet.expr1 - __use__401.snippet0.snippet.snippet.join)(__use__401.snippet0.snippet.snippet.expr0 - &__use__401.snippet0.snippet.snippet.join)(__use__401.snippet0.snippet.snippet.expr - &__use__401.snippet0.snippet.snippet.join)] - &__use__401.snippet0.snippet.join)(__use__401.snippet0.snippet.expr - &__use__401.snippet0.snippet.join)] - __use__401.snippet0.call - __use__401.snippet0.call.iftype
            // __use__40.snippet.snippet.noop - [(__use__40.snippet.snippet.snippet0.noop - [(__use__40.snippet.snippet.snippet0.expr0 - __use__40.snippet.snippet.snippet0.join)(__use__40.snippet.snippet.snippet0.snippet.noop - [(__use__40.snippet.snippet.snippet0.snippet.expr1 - __use__40.snippet.snippet.snippet0.snippet.join)(__use__40.snippet.snippet.snippet0.snippet.expr0 - &__use__40.snippet.snippet.snippet0.snippet.join)(__use__40.snippet.snippet.snippet0.snippet.expr - &__use__40.snippet.snippet.snippet0.snippet.join)] - &__use__40.snippet.snippet.snippet0.join)] - __use__40.snippet.snippet.join)(__use__40.snippet.snippet.snippet.noop - [(__use__40.snippet.snippet.snippet.expr1 - __use__40.snippet.snippet.snippet.join)(__use__40.snippet.snippet.snippet.expr0 - &__use__40.snippet.snippet.snippet.join)(__use__40.snippet.snippet.snippet.expr - &__use__40.snippet.snippet.snippet.join)] - &__use__40.snippet.snippet.join)(__use__40.snippet.snippet.expr - &__use__40.snippet.snippet.join)] - __use__40.snippet.call - __use__40.snippet.call.iftype
            // __use__4.snippet0.snippet.noop - [(__use__4.snippet0.snippet.snippet0.noop - [(__use__4.snippet0.snippet.snippet0.expr0 - __use__4.snippet0.snippet.snippet0.join)(__use__4.snippet0.snippet.snippet0.snippet.noop - [(__use__4.snippet0.snippet.snippet0.snippet.expr1 - __use__4.snippet0.snippet.snippet0.snippet.join)(__use__4.snippet0.snippet.snippet0.snippet.expr0 - &__use__4.snippet0.snippet.snippet0.snippet.join)(__use__4.snippet0.snippet.snippet0.snippet.expr - &__use__4.snippet0.snippet.snippet0.snippet.join)] - &__use__4.snippet0.snippet.snippet0.join)] - __use__4.snippet0.snippet.join)(__use__4.snippet0.snippet.snippet.noop - [(__use__4.snippet0.snippet.snippet.expr1 - __use__4.snippet0.snippet.snippet.join)(__use__4.snippet0.snippet.snippet.expr0 - &__use__4.snippet0.snippet.snippet.join)(__use__4.snippet0.snippet.snippet.expr - &__use__4.snippet0.snippet.snippet.join)] - &__use__4.snippet0.snippet.join)(__use__4.snippet0.snippet.expr - &__use__4.snippet0.snippet.join)] - __use__4.snippet0.call - __use__4.snippet0.call.iftype
            // __use__400.snippet0.snippet.noop - [(__use__400.snippet0.snippet.snippet0.noop - [(__use__400.snippet0.snippet.snippet0.expr0 - __use__400.snippet0.snippet.snippet0.join)(__use__400.snippet0.snippet.snippet0.snippet.noop - [(__use__400.snippet0.snippet.snippet0.snippet.expr1 - __use__400.snippet0.snippet.snippet0.snippet.join)(__use__400.snippet0.snippet.snippet0.snippet.expr0 - &__use__400.snippet0.snippet.snippet0.snippet.join)(__use__400.snippet0.snippet.snippet0.snippet.expr - &__use__400.snippet0.snippet.snippet0.snippet.join)] - &__use__400.snippet0.snippet.snippet0.join)] - __use__400.snippet0.snippet.join)(__use__400.snippet0.snippet.snippet.noop - [(__use__400.snippet0.snippet.snippet.expr1 - __use__400.snippet0.snippet.snippet.join)(__use__400.snippet0.snippet.snippet.expr0 - &__use__400.snippet0.snippet.snippet.join)(__use__400.snippet0.snippet.snippet.expr - &__use__400.snippet0.snippet.snippet.join)] - &__use__400.snippet0.snippet.join)(__use__400.snippet0.snippet.expr - &__use__400.snippet0.snippet.join)] - __use__400.snippet0.call - __use__400.snippet0.call.iftype
            ///////////////////////////////////////////////////////////////////

            void _mergeBetaHandler(dssp.DefaultSubmitResponseType message)
            {
                JoinGamma a = new JoinGamma();
                a.Z = 0;
                a.Y = 0;
                a.X = 1;
                JoinDelta b = new JoinDelta();
                b.Angle = FloatCast(State.Gripper5);
                b.Axis = a;
                JoinGamma c = new JoinGamma();
                c.Z = 0;
                c.Y = 0;
                c.X = 0;
                articulatedarm.SetJointTargetPoseRequest request = new articulatedarm.SetJointTargetPoseRequest();
                request.TargetOrientation = (Microsoft.Robotics.PhysicalModel.Proxy.AxisAngle)b;
                request.TargetPosition = (Microsoft.Robotics.PhysicalModel.Proxy.Vector3)c;
                request.JointName = @"Gripper-Joint5";

                Increment();
                Activate(
                    ccr.Arbiter.Choice(
                        LynxMotionLynx6ArmPort.SetJointTargetPose(request),
                        delegate
                        {
                            Decrement();
                        },
                        OnSetJointTargetPoseFault
                    )
                );

                JoinGamma d = new JoinGamma();
                d.Z = 0;
                d.Y = 0;
                d.X = 1;
                JoinDelta e = new JoinDelta();
                e.Angle = FloatCast(State.WristRotate4);
                e.Axis = d;
                JoinGamma f = new JoinGamma();
                f.Z = 0;
                f.Y = 0;
                f.X = 0;
                articulatedarm.SetJointTargetPoseRequest requestA = new articulatedarm.SetJointTargetPoseRequest();
                requestA.TargetOrientation = (Microsoft.Robotics.PhysicalModel.Proxy.AxisAngle)e;
                requestA.TargetPosition = (Microsoft.Robotics.PhysicalModel.Proxy.Vector3)f;
                requestA.JointName = @"WristRotate-Joint4";

                Increment();
                Activate(
                    ccr.Arbiter.Choice(
                        LynxMotionLynx6ArmPort.SetJointTargetPose(requestA),
                        delegate
                        {
                            Decrement();
                        },
                        OnSetJointTargetPose1Fault
                    )
                );

                JoinGamma g = new JoinGamma();
                g.Z = 0;
                g.Y = 0;
                g.X = 1;
                JoinDelta h = new JoinDelta();
                h.Angle = FloatCast(State.Wrist3);
                h.Axis = g;
                JoinGamma i = new JoinGamma();
                i.Z = 0;
                i.Y = 0;
                i.X = 0;
                articulatedarm.SetJointTargetPoseRequest requestB = new articulatedarm.SetJointTargetPoseRequest();
                requestB.TargetOrientation = (Microsoft.Robotics.PhysicalModel.Proxy.AxisAngle)h;
                requestB.TargetPosition = (Microsoft.Robotics.PhysicalModel.Proxy.Vector3)i;
                requestB.JointName = @"Wrist-Joint3";

                Increment();
                Activate(
                    ccr.Arbiter.Choice(
                        LynxMotionLynx6ArmPort.SetJointTargetPose(requestB),
                        delegate
                        {
                            Decrement();
                        },
                        OnSetJointTargetPose2Fault
                    )
                );

                JoinGamma j = new JoinGamma();
                j.Z = 0;
                j.Y = 0;
                j.X = 1;
                JoinDelta k = new JoinDelta();
                k.Angle = FloatCast(State.Elbow2);
                k.Axis = j;
                JoinGamma l = new JoinGamma();
                l.Z = 0;
                l.Y = 0;
                l.X = 0;
                articulatedarm.SetJointTargetPoseRequest requestC = new articulatedarm.SetJointTargetPoseRequest();
                requestC.TargetOrientation = (Microsoft.Robotics.PhysicalModel.Proxy.AxisAngle)k;
                requestC.TargetPosition = (Microsoft.Robotics.PhysicalModel.Proxy.Vector3)l;
                requestC.JointName = @"Elbow-Joint2";

                Increment();
                Activate(
                    ccr.Arbiter.Choice(
                        LynxMotionLynx6ArmPort.SetJointTargetPose(requestC),
                        delegate
                        {
                            Decrement();
                        },
                        OnSetJointTargetPose3Fault
                    )
                );

                JoinGamma m = new JoinGamma();
                m.Z = 0;
                m.Y = 0;
                m.X = 1;
                JoinDelta n = new JoinDelta();
                n.Angle = FloatCast(State.Shoulder1);
                n.Axis = m;
                JoinGamma o = new JoinGamma();
                o.Z = 0;
                o.Y = 0;
                o.X = 0;
                articulatedarm.SetJointTargetPoseRequest requestD = new articulatedarm.SetJointTargetPoseRequest();
                requestD.TargetOrientation = (Microsoft.Robotics.PhysicalModel.Proxy.AxisAngle)n;
                requestD.TargetPosition = (Microsoft.Robotics.PhysicalModel.Proxy.Vector3)o;
                requestD.JointName = @"Shoulder-Joint1";

                Increment();
                Activate(
                    ccr.Arbiter.Choice(
                        LynxMotionLynx6ArmPort.SetJointTargetPose(requestD),
                        OnSetJointTargetPoseSuccess,
                        OnSetJointTargetPose4Fault
                    )
                );

                JoinGamma p = new JoinGamma();
                p.Z = 0;
                p.Y = 0;
                p.X = 1;
                JoinDelta q = new JoinDelta();
                q.Angle = FloatCast(State.Base0);
                q.Axis = p;
                JoinGamma r = new JoinGamma();
                r.Z = 0;
                r.Y = 0;
                r.X = 0;
                articulatedarm.SetJointTargetPoseRequest requestE = new articulatedarm.SetJointTargetPoseRequest();
                requestE.TargetOrientation = (Microsoft.Robotics.PhysicalModel.Proxy.AxisAngle)q;
                requestE.TargetPosition = (Microsoft.Robotics.PhysicalModel.Proxy.Vector3)r;
                requestE.JointName = @"Base-Joint0";

                Increment();
                Activate(
                    ccr.Arbiter.Choice(
                        LynxMotionLynx6ArmPort.SetJointTargetPose(requestE),
                        delegate
                        {
                            Decrement();
                        },
                        OnSetJointTargetPose5Fault
                    )
                );

                Decrement();
            }

            void OnSetJointTargetPoseFault(soap.Fault response)
            {

                Increment();
                _mergeGamma.Post(response);

                Decrement();
            }

            void OnSetJointTargetPose1Fault(soap.Fault response)
            {
                Decrement();
            }

            void OnSetJointTargetPose2Fault(soap.Fault response)
            {
                Decrement();
            }

            void OnSetJointTargetPose3Fault(soap.Fault response)
            {
                Decrement();
            }

            void OnSetJointTargetPoseSuccess(dssp.DefaultUpdateResponseType response)
            {
                Decrement();
            }

            void OnSetJointTargetPose4Fault(soap.Fault response)
            {
                Decrement();
            }

            void OnSetJointTargetPose5Fault(soap.Fault response)
            {

                Increment();
                _mergeGamma.Post(response);

                Decrement();
            }

            ccr.Port<soap.Fault> _mergeGamma = new ccr.Port<soap.Fault>();

            ///////////////////////////////////////////////////////////////////
            // __use__1.snippet0.snippet.noop - __use__1.snippet0.snippet.expr - __use__1.snippet0.snippet.join
            ///////////////////////////////////////////////////////////////////

            void _mergeGammaHandler(soap.Fault message)
            {
                Increment();
                _joinBetaPorts[0].Post(null);

                Decrement();
            }

            class JoinAlpha
            {
                public int Interval;

                public JoinAlpha()
                {
                }

                public JoinAlpha(object[] args)
                {
                    Interval = (int)args[0];
                }

                public static explicit operator timer.SetTimerRequest(JoinAlpha join)
                {
                    timer.SetTimerRequest request = new timer.SetTimerRequest();

                    request.Interval = join.Interval;
                    return request;
                }
            }

            ccr.Port<object>[] _joinAlphaPorts = new ccr.Port<object>[1]{
                new ccr.Port<object>()
            };

            class JoinDelta
            {
                public JoinGamma Axis;
                public float Angle;

                public JoinDelta()
                {
                }

                public JoinDelta(object[] args)
                {
                    Axis = (JoinGamma)args[0];
                    Angle = (float)args[1];
                }

                public static explicit operator Microsoft.Robotics.PhysicalModel.Proxy.AxisAngle(JoinDelta join)
                {
                    Microsoft.Robotics.PhysicalModel.Proxy.AxisAngle request = new Microsoft.Robotics.PhysicalModel.Proxy.AxisAngle();

                    request.Axis = (Microsoft.Robotics.PhysicalModel.Proxy.Vector3)join.Axis;
                    request.Angle = join.Angle;
                    return request;
                }
            }

            ccr.Port<object>[] _joinDeltaPorts = new ccr.Port<object>[2]{
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            class JoinEpsilon
            {
                public string JointName;
                public string TargetPosition;
                public string TargetOrientation;

                public JoinEpsilon()
                {
                }

                public JoinEpsilon(object[] args)
                {
                    JointName = args[0].ToString();
                    TargetPosition = args[1].ToString();
                    TargetOrientation = args[2].ToString();
                }
            }

            ccr.Port<object>[] _joinEpsilonPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            class JoinBeta
            {
                public object Synchronous;

                public JoinBeta()
                {
                }

                public JoinBeta(object[] args)
                {
                    Synchronous = (object)args[0];
                }

                public static explicit operator sound.BeepRequest(JoinBeta join)
                {
                    sound.BeepRequest request = new sound.BeepRequest();

                    request.Synchronous = (bool)join.Synchronous;
                    return request;
                }
            }

            ccr.Port<object>[] _joinBetaPorts = new ccr.Port<object>[1]{
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _secondJoinAlphaPorts = new ccr.Port<object>[1]{
                new ccr.Port<object>()
            };

            class JoinGamma
            {
                public int X;
                public int Y;
                public int Z;

                public JoinGamma()
                {
                }

                public JoinGamma(object[] args)
                {
                    X = (int)args[0];
                    Y = (int)args[1];
                    Z = (int)args[2];
                }

                public static explicit operator Microsoft.Robotics.PhysicalModel.Proxy.Vector3(JoinGamma join)
                {
                    Microsoft.Robotics.PhysicalModel.Proxy.Vector3 request = new Microsoft.Robotics.PhysicalModel.Proxy.Vector3();

                    request.X = (float)join.X;
                    request.Y = (float)join.Y;
                    request.Z = (float)join.Z;
                    return request;
                }
            }

            ccr.Port<object>[] _joinGammaPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _secondJoinGammaPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _secondJoinDeltaPorts = new ccr.Port<object>[2]{
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _secondJoinEpsilonPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _thirdJoinGammaPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _fourthJoinGammaPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _thirdJoinDeltaPorts = new ccr.Port<object>[2]{
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _thirdJoinEpsilonPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _fifthJoinGammaPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _sixthJoinGammaPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _fourthJoinDeltaPorts = new ccr.Port<object>[2]{
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _fourthJoinEpsilonPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _seventhJoinGammaPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _eighthJoinGammaPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _fifthJoinDeltaPorts = new ccr.Port<object>[2]{
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _fifthJoinEpsilonPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _ninthJoinGammaPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _tenthJoinGammaPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _sixthJoinDeltaPorts = new ccr.Port<object>[2]{
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _sixthJoinEpsilonPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _eleventhJoinGammaPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };

            ccr.Port<object>[] _twelfthJoinGammaPorts = new ccr.Port<object>[3]{
                new ccr.Port<object>(),
                new ccr.Port<object>(),
                new ccr.Port<object>()
            };
        }

        #endregion

        #region Handler utility base class

        class HandlerBase : ccr.CcrServiceBase
        {
            ccr.Port<ccr.EmptyValue> _complete = new ccr.Port<ccr.EmptyValue>();
            ccr.Port<ccr.EmptyValue> _shutdown = new ccr.Port<ccr.EmptyValue>();
            List<ccr.Port<object>[]> _joins = new List<ccr.Port<object>[]>();
            ArmMoverService _service;
            int _count;

            public HandlerBase(ArmMoverService service, ccr.DispatcherQueue queue)
                : base(queue)
            {
                _service = service;
            }

            protected ArmMoverState State
            {
                get { return _service._state; }
            }

            bool _stateChanged;

            public bool StateChanged
            {
                get { return _stateChanged; }
                set { _stateChanged = value; }
            }

            protected timer.TimerOperations TimerPort
            {
                get { return _service._timerPort; }
            }

            protected sound.SoundOperations SoundPlayerPort
            {
                get { return _service._soundPlayerPort; }
            }

            protected timer.TimerOperations Timer0Port
            {
                get { return _service._timer0Port; }
            }

            protected xinputgamepad.XInputGamepadOperations XInputControllerPort
            {
                get { return _service._xInputControllerPort; }
            }

            protected articulatedarm.ArticulatedArmOperations LynxMotionLynx6ArmPort
            {
                get { return _service._lynxMotionLynx6ArmPort; }
            }

            public ccr.Port<ccr.EmptyValue> Complete
            {
                get { return _complete; }
            }

            protected void Increment()
            {
                System.Threading.Interlocked.Increment(ref _count);
            }

            protected void Decrement()
            {
                int offset = 0;

                foreach (ccr.Port<object>[] join in _joins)
                {
                    bool complete = true;
                    int joinCount = 0;

                    foreach (ccr.Port<object> sink in join)
                    {
                        if (sink.ItemCount != 0)
                        {
                            joinCount += sink.ItemCount;
                        }
                        else
                        {
                            complete = false;
                        }
                    }
                    if (complete == false)
                    {
                        offset += joinCount;
                    }
                }

                if (System.Threading.Interlocked.Decrement(ref _count) <= offset)
                {
                    _shutdown.Post(ccr.EmptyValue.SharedInstance);
                    _complete.Post(ccr.EmptyValue.SharedInstance);
                }
            }

            protected void Decrement(int count)
            {
                for(int i = 0; i < count; i++)
                {
                    Decrement();
                }
            }

            protected void RegisterJoin(ccr.Port<object>[] join)
            {
                _joins.Add(join);
            }

            protected ccr.ITask WaitUntilComplete()
            {
                return ccr.Arbiter.Receive(false, _shutdown, NullDelegate);
            }

            protected static void NullDelegate(ccr.EmptyValue token)
            {
            }

            protected void SendNotification<T>(object notification)
                where T : dssp.DsspOperation, new()
            {
                _service.SendNotification<T>(_service._subMgr, notification);
            }

            protected void FaultHandler(soap.Fault fault, string msg)
            {
                _service.LogError(null, msg, fault);
            }

            protected static string Stringize(object obj)
            {
                if (obj == null)
                {
                    return string.Empty;
                }
                else
                {
                    return obj.ToString();
                }
            }

            protected void UnhandledResponse(W3C.Soap.Fault fault)
            {
                _service.LogError("Unhandled fault response from partner service", fault);
                Decrement();
            }

            protected void UnhandledResponse<T>(T response)
            {
                Decrement();
            }

            #region Type Cast Functions

            protected static bool BoolCast(object obj)
            {
                if (obj != null && obj is IConvertible)
                {
                    try
                    {
                        return ((IConvertible)obj).ToBoolean(System.Globalization.CultureInfo.InvariantCulture);
                    }
                    catch (FormatException)
                    {
                    }
                }
                return false;
            }

            protected static byte ByteCast(object obj)
            {
                if (obj != null && obj is IConvertible)
                {
                    try
                    {
                        return ((IConvertible)obj).ToByte(System.Globalization.CultureInfo.InvariantCulture);
                    }
                    catch (FormatException)
                    {
                    }
                }
                return 0;
            }

            protected static char CharCast(object obj)
            {
                if (obj != null && obj is IConvertible)
                {
                    try
                    {
                        return ((IConvertible)obj).ToChar(System.Globalization.CultureInfo.InvariantCulture);
                    }
                    catch (FormatException)
                    {
                    }
                }
                return '\0';
            }

            protected static decimal DecimalCast(object obj)
            {
                if (obj != null && obj is IConvertible)
                {
                    try
                    {
                        return ((IConvertible)obj).ToDecimal(System.Globalization.CultureInfo.InvariantCulture);
                    }
                    catch (FormatException)
                    {
                    }
                }
                return 0;
            }

            protected static double DoubleCast(object obj)
            {
                if (obj != null && obj is IConvertible)
                {
                    try
                    {
                        return ((IConvertible)obj).ToDouble(System.Globalization.CultureInfo.InvariantCulture);
                    }
                    catch (FormatException)
                    {
                    }
                }
                return 0;
            }

            protected static float FloatCast(object obj)
            {
                if (obj != null && obj is IConvertible)
                {
                    try
                    {
                        return ((IConvertible)obj).ToSingle(System.Globalization.CultureInfo.InvariantCulture);
                    }
                    catch (FormatException)
                    {
                    }
                }
                return 0;
            }

            protected static int IntCast(object obj)
            {
                if (obj != null && obj is IConvertible)
                {
                    try
                    {
                        return ((IConvertible)obj).ToInt32(System.Globalization.CultureInfo.InvariantCulture);
                    }
                    catch (FormatException)
                    {
                    }
                }
                return 0;
            }

            protected static long LongCast(object obj)
            {
                if (obj != null && obj is IConvertible)
                {
                    try
                    {
                        return ((IConvertible)obj).ToInt64(System.Globalization.CultureInfo.InvariantCulture);
                    }
                    catch (FormatException)
                    {
                    }
                }
                return 0;
            }

            protected static sbyte SByteCast(object obj)
            {
                if (obj != null && obj is IConvertible)
                {
                    try
                    {
                        return ((IConvertible)obj).ToSByte(System.Globalization.CultureInfo.InvariantCulture);
                    }
                    catch (FormatException)
                    {
                    }
                }
                return 0;
            }

            protected static short ShortCast(object obj)
            {
                if (obj != null && obj is IConvertible)
                {
                    try
                    {
                        return ((IConvertible)obj).ToInt16(System.Globalization.CultureInfo.InvariantCulture);
                    }
                    catch (FormatException)
                    {
                    }
                }
                return 0;
            }

            protected static uint UIntCast(object obj)
            {
                if (obj != null && obj is IConvertible)
                {
                    try
                    {
                        return ((IConvertible)obj).ToUInt32(System.Globalization.CultureInfo.InvariantCulture);
                    }
                    catch (FormatException)
                    {
                    }
                }
                return 0;
            }

            protected static ulong ULongCast(object obj)
            {
                if (obj != null && obj is IConvertible)
                {
                    try
                    {
                        return ((IConvertible)obj).ToUInt64(System.Globalization.CultureInfo.InvariantCulture);
                    }
                    catch (FormatException)
                    {
                    }
                }
                return 0;
            }

            protected static ushort UShortCast(object obj)
            {
                if (obj != null && obj is IConvertible)
                {
                    try
                    {
                        return ((IConvertible)obj).ToUInt16(System.Globalization.CultureInfo.InvariantCulture);
                    }
                    catch (FormatException)
                    {
                    }
                }
                return 0;
            }

            #endregion

            #region List Functions

            protected List<T> ListAdd<T>(List<T> list, T item)
            {
                List<T> output = new List<T>(list);
                output.Add(item);
                return output;
            }

            protected List<T> ListConcat<T>(List<T> head, List<T> tail)
            {
                List<T> output = new List<T>(head);
                output.AddRange(tail);
                return output;
            }

            protected int ListIndex<T>(List<T> list, T item)
            {
                return list.IndexOf(item);
            }

            protected List<T> ListRemove<T>(List<T> list, int index)
            {
                List<T> output = new List<T>(list);
                output.RemoveAt(index);
                return output;
            }

            protected List<T> ListReverse<T>(List<T> list)
            {
                List<T> output = new List<T>(list);
                output.Reverse();
                return output;
            }

            protected List<T> ListSort<T>(List<T> list)
            {
                List<T> output = new List<T>(list);
                output.Sort();
                return output;
            }

            protected List<T> ListInsert<T>(List<T> list, T item, int index)
            {
                List<T> output = new List<T>(list);
                output.Insert(index, item);
                return output;
            }

            #endregion
        }

        #endregion
    }
}
